package com.ebeijia.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ebeijia.exception.WebInfoException;
import com.ebeijia.util.LoggerUtil;
import com.ebeijia.util.PropertiesUtils;

@Controller
@RequestMapping("/")
public class FileDownloadController {

	@RequestMapping("/image/{fileName}.{format}")
	public void downImageFile(@PathVariable String fileName, @PathVariable String format,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Pattern excludeUrls = Pattern.compile("^(jpg|bmp|png){1}$",
				Pattern.CASE_INSENSITIVE);
		Matcher m = excludeUrls.matcher(format);
		if (!m.matches()) {
			return;
		}
		download(request, response, "/image/" + fileName + "." + format);

	}

	private void download(HttpServletRequest request,
			HttpServletResponse response, String path)
			throws UnsupportedEncodingException {
		File downloadFile = getFile(request, path);
		if (downloadFile == null) {
			LoggerUtil.info(path+" 文件不存在");
			return;
		}
		ServletOutputStream os = null;
		BufferedOutputStream out = null;
		BufferedInputStream bis = null;
		byte b[] = new byte[1024];
		try {
			os = response.getOutputStream();
			out = new BufferedOutputStream(os);
			bis = new BufferedInputStream(new FileInputStream(downloadFile));
			try {
				int n = 0;
				while ((n = bis.read(b, 0, 1024)) != -1) {
					out.write(b, 0, n);
				}
				out.flush();
			} catch (IOException ie) {
			}
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage(), e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LoggerUtil.error(e.getMessage(), e);
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					LoggerUtil.error(e.getMessage(), e);
				}
			}
		}
	}

	private File getFile(HttpServletRequest request, String path) {
		String fileTmpPath = PropertiesUtils.getProperties("image.upload.path");
		File file = new File(fileTmpPath + path);
		if (!file.exists()) {
			return null;
		}
		return file;

	}

}
